package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName: String2StringArr
 * @Author: WangEnzhao
 * @Description: 将String转换为String数组或者相反
 * @CreateTime: 2021/12/11:02:00
 */

@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class String2StringArr implements TypeHandler<String[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @Author: WangEnzhao
     * @Description: 将string数组转换为string，插入数据库时候使用
     * @CreateTime:
     * @Param:
     * @return:
     **/
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        String result = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i, result);
    }

    /**
     * @Author: WangEnzhao
     * @Description: 将string转换为string数组，查询时候使用
     * @CreateTime:
     * @Param:
     * @return:
     **/
    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        return transfer(string);
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        return transfer(string);
    }

    @SneakyThrows
    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        return transfer(string);
    }

    private String[] transfer(String result) throws JsonProcessingException {
        if(result == null || "".equals(result)){
            return new String[0];
        }

        String[] strings = objectMapper.readValue(result,String[].class);
        return strings;
    }
}
